import dayjs from 'dayjs'


/**
 *  月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *  年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)。
 */
const _formatDate = function(date, fmt) {
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" +
			o[k]).substr(("" + o[k]).length)));
	return fmt;
};

// 接口提交数据扁平化
export function objectToFormData(obj, parentKey = '', result = []) {

  for (const key in obj) {
      if (!obj.hasOwnProperty(key)) continue;
      const fullKey = parentKey ? `${parentKey}[${key}]` : key;
      const value = obj[key];

      if (Array.isArray(value)) {
        value.forEach(item => {
          result.push(`${encodeURIComponent(fullKey)}[]=${encodeURIComponent(item)}`);
        });
      } else if (typeof value === 'object') {
        objectToFormData(value, fullKey, result);
      } else {
        result.push(`${encodeURIComponent(fullKey)}=${encodeURIComponent(value)}`);
      }
    }
    return result.join('&');
}



/**
 * 1）7天之内的日期显示逻辑是：今天、昨天(-1d)、前天(-2d)、星期？（只显示总计7天之内的星期数，即<=-4d）；
 * 2）7天之外（即>7天）的逻辑：直接显示完整日期时间。
 * @param  {[long]} timestamp 时间戳（单位：毫秒），形如：1550789954260
 * @return {string} 输出格式形如：“刚刚”、“10:30”、“昨天 12:04”、“前天 20:51”、“星期二”、“2019/2/21 12:09”等形式
 */
export function getTimeStringAutoShort(timestamp, mustIncludeTime) {

	// 当前时间
	var currentDate = new Date();
	// 目标判断时间
	var srcDate = new Date(parseInt(timestamp));

	var currentYear = currentDate.getFullYear();
	var currentMonth = (currentDate.getMonth() + 1);
	var currentDateD = currentDate.getDate();

	var srcYear = srcDate.getFullYear();
	var srcMonth = (srcDate.getMonth() + 1);
	var srcDateD = srcDate.getDate();

	var ret = "";

	// 要额外显示的时间分钟
	var timeExtraStr = (mustIncludeTime ? " " + _formatDate(srcDate, "hh:mm") : "");

	// 当年
	if (currentYear == srcYear) {
		var currentTimestamp = currentDate.getTime();
		var srcTimestamp = timestamp;
		// 相差时间（单位：毫秒）
		var deltaTime = (currentTimestamp - srcTimestamp);
		// 当天（月份和日期一致才是）
		if (currentMonth == srcMonth && currentDateD == srcDateD) {
			// 时间相差60秒以内
			if (deltaTime < 60 * 1000)
				ret = "刚刚";
			// 否则当天其它时间段的，直接显示“时:分”的形式
			else
				ret = _formatDate(srcDate, "hh:mm");
		}
		// 当年 && 当天之外的时间（即昨天及以前的时间）
		else {
			// 昨天（以“现在”的时候为基准-1天）
			var yesterdayDate = new Date();
			yesterdayDate.setDate(yesterdayDate.getDate() - 1);

			// 前天（以“现在”的时候为基准-2天）
			var beforeYesterdayDate = new Date();
			beforeYesterdayDate.setDate(beforeYesterdayDate.getDate() - 2);

			// 用目标日期的“月”和“天”跟上方计算出来的“昨天”进行比较，是最为准确的（如果用时间戳差值
			// 的形式，是不准确的，比如：现在时刻是2019年02月22日1:00、而srcDate是2019年02月21日23:00，
			// 这两者间只相差2小时，直接用“deltaTime/(3600 * 1000)” > 24小时来判断是否昨天，就完全是扯蛋的逻辑了）
			if (srcMonth == (yesterdayDate.getMonth() + 1) && srcDateD == yesterdayDate.getDate())
				ret = "昨天" + timeExtraStr; // -1d
			// “前天”判断逻辑同上
			else if (srcMonth == (beforeYesterdayDate.getMonth() + 1) && srcDateD == beforeYesterdayDate.getDate())
				ret = "前天" + timeExtraStr; // -2d
			else {
				// 跟当前时间相差的小时数
				var deltaHour = (deltaTime / (3600 * 1000));

				ret = dayjs(srcDate).format('MM-DD') + timeExtraStr;

				// 如果小于或等 7*24小时就显示星期几
				// if (deltaHour <= 7 * 24) {
				// 	var weekday = new Array(7);
				// 	weekday[0] = "星期日";
				// 	weekday[1] = "星期一";
				// 	weekday[2] = "星期二";
				// 	weekday[3] = "星期三";
				// 	weekday[4] = "星期四";
				// 	weekday[5] = "星期五";
				// 	weekday[6] = "星期六";

				// 	// 取出当前是星期几
				// 	var weedayDesc = weekday[srcDate.getDay()];
				// 	ret = weedayDesc + timeExtraStr;
				// }
				// // 否则直接显示完整日期时间
				// else {
				// 	ret = dayjs(srcDate).format('MM-DD') + timeExtraStr;
				// }

			}
		}
	}
	// 往年
	else {
		ret = dayjs(srcDate).format('YYYY-MM-DD') + timeExtraStr;
	}

	return ret;
};


function getDataColumn(main, uri, selection, selectionArgs) {
	plus.android.importClass(main.getContentResolver());
	let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs,
		null);
	plus.android.importClass(cursor);
	if (cursor != null && cursor.moveToFirst()) {
		var column_index = cursor.getColumnIndexOrThrow('_data');
		var result = cursor.getString(column_index)
		cursor.close();
		return result;
	}
	return null;
}

export function formatFileSize(fileSize) {
	if (fileSize < 1024) {
		return fileSize + ' B';
	} else if (fileSize < 1024 * 1024) {
		return (fileSize / 1024).toFixed(2) + ' KB';
	} else if (fileSize < 1024 * 1024 * 1024) {
		return (fileSize / (1024 * 1024)).toFixed(2) + ' MB';
	} else {
		return (fileSize / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
	}
}

export function setIcon(fileName) {
	const str = fileName.split('.');
	const fileType = str[str.length-1];
	switch (fileType) {
		case 'dir':
			return '/static/img/dir.760656b.jpg';
			break;
		case 'pdf':
			return '/static/img/pdf.1ab8412.jpg';
			break;
		case 'ppt':
			return '/static/img/ppt.12ba29b.jpg';
			break;
		case 'doc':
		case 'docx':
			return '/static/img/word.086531c.jpg';
			break;
		case 'xlsx':
		case 'xls‌':
		case 'xlsm':
		case 'csv':
		case 'ods‌':
			return '/static/img/excel.a9ec8fc.jpg';
			break;
		default:
			return ''
			break;
	}
}

export function chooseFile(callback, acceptType) {

	var CODE_REQUEST = 1000;
	var main = plus.android.runtimeMainActivity();
	if (plus.os.name == 'Android') {
		var Intent = plus.android.importClass('android.content.Intent');
		var intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		if (acceptType) {
			intent.setType(acceptType);
		} else {
			intent.setType("*/*");
		}
		main.onActivityResult = (requestCode, resultCode, data) => {
			if (requestCode == CODE_REQUEST) {
				const uri = data.getData();
				plus.android.importClass(uri);
				const Build = plus.android.importClass('android.os.Build');
				const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
				const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');

				if (isKitKat && DocumentsContract.isDocumentUri(main, uri)) {
					if ("com.android.externalstorage.documents" == uri.getAuthority()) {
						var docId = DocumentsContract.getDocumentId(uri);
						var split = docId.split(":");
						var type = split[0];

						if ("primary" == type) {
							var Environment = plus.android.importClass('android.os.Environment');
							callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
						} else {
							var System = plus.android.importClass('java.lang.System');
							var sdPath = System.getenv("SECONDARY_STORAGE");
							if (sdPath) {
								callback(sdPath + "/" + split[1]);
							}
						}
					} else if ("com.android.providers.downloads.documents" == uri.getAuthority()) {
						var id = DocumentsContract.getDocumentId(uri);
						console.log(id)
						var ContentUris = plus.android.importClass('android.content.ContentUris');
						console.log(ContentUris)
						var contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
						//    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
						// console.log(main)
						console.log(contentUri)
						callback(getDataColumn(main, contentUri, null, null));
					} else if ("com.android.providers.media.documents" == uri.getAuthority()) {
						var docId = DocumentsContract.getDocumentId(uri);
						var split = docId.split(":");
						console.log(split);
						var type = split[0];
						console.log(type);
						var MediaStore = plus.android.importClass('android.provider.MediaStore');
						if ("image" == type) {
							contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
						} else if ("video" == type) {
							contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
						} else if ("audio" == type) {
							contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
						} else {
							contentUri = MediaStore.Files.getContentUri("external");
						}

						var selection = "_id=?";
						var selectionArgs = new Array();
						selectionArgs[0] = split[1];

						callback(getDataColumn(main, contentUri, selection, selectionArgs));
					}
				} else if ("content" == uri.getScheme()) {
					callback(getDataColumn(main, uri, null, null));
				} else if ("file" == uri.getScheme()) {
					callback(uri.getPath());
				}
			}
		}
		main.startActivityForResult(intent, CODE_REQUEST);
	}
}

/**
 * 设置文件类型
 * @param 后缀
 */
const file_type = {
	word: {
		data: ['doc', 'docx'],
		preview: true
	},
	excel: {
		data: ['xls', 'xlsx'],
			preview: true
	},
	ppt: {
		data: ['ppt', 'pptx'],
		preview: true
	},
	pdf: {
		data: ['pdf'],
		preview: true
	},
	txt: {
		data: ['txt'],
		preview: true
	},
	image: {
		data: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'],
		preview: true
	},
	video: {
		data: ['mp4', 'm3u8', 'rmvb', 'avi', 'swf', '3gp', 'mkv', 'flv'],
		preview: false
	},
	audio: {
		data: ['mp3', 'wav', 'wma', 'ogg', 'aac', 'flac'],
		preview: false
	},
	archive: {
		data: ['zip', 'rar', '7z'],
		preview: false
	},
}

export function fileTypeFormat (suffix)  {
	let fileType = '';
	for (let key in file_type) {
			for (let i = 0; i < file_type[key].data.length; i++) {
					if(suffix === file_type[key].data[i]) {
							fileType = key;
					}
			}
	}
	if(fileType === '') {
			return 'other'
	}else {
			return fileType
	}
}


/**
 * 处理图片 URL：去除 thumb_ 前缀 + 替换 http -> https
 * @param {string} url - 原始图片地址
 * @returns {string}
 */
export function processImageUrl(url) {
	if (!url) return '';
	if(typeof url !== 'string') return;
	let newUrl
	// 替换协议
	 newUrl = url.replace('http:', 'https:').replace(':81', ':88');

	return newUrl;
}
export function fixImageSrc(html, baseUrl = "https://chat.mfarmers.com:88") {
  if (!html) return '';
  return html.replace(/<img\s+[^>]*src=["']([^"']+)["'][^>]*>/gi, (match, src) => {
    // 如果 src 已经包含 http(s)，保持原样
    if (/^https?:\/\//i.test(src)) {
      return match;
    }
    // 如果是 // 开头（协议相对路径），也保持
    if (/^\/\//.test(src)) {
      return match;
    }
    // 拼接域名
    const fixedSrc = baseUrl.replace(/\/+$/, '') + '/' + src.replace(/^\/+/, '');
    return match.replace(src, fixedSrc);
  });
}
/**
 * 根据图片原始宽高，计算按固定宽度缩放后的宽高
 * @param {String} imgUrl - 图片地址
 * @returns {Promise<{width: Number, height: Number}>} 缩放后的宽高
 */
export function getScaledImageSize(imgUrl) {
	if(typeof imgUrl !== 'string') return;
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: imgUrl,
      success: (res) => {
        uni.getSystemInfo({
          success(sys) {
            const maxChatWidth = sys.windowWidth * 0.5;   // 聊天气泡最大宽度
            const maxChatHeight = sys.windowHeight * 0.5; // 聊天气泡最大高度
            const thumbWidth = maxChatWidth * 0.4;        // 缩略图宽度（长图用）
            const thumbHeight = maxChatHeight * 0.4;      // 缩略图高度（超宽图用）

            const naturalW = res.width;
            const naturalH = res.height;

            let width = 0;
            let height = 0;

            // ---- 情况 1：图片本身尺寸不大，直接原图 ----
            if (naturalW <= maxChatWidth && naturalH <= maxChatHeight) {
              resolve({
                width: naturalW,
                height: naturalH
              });
              return;
            }

            // ---- 情况 2：竖向长图（高度远大于宽度） ----
            if (naturalH / naturalW > 2) {
              width = thumbWidth;
              height = thumbWidth * (naturalH / naturalW);  // 根据宽高比缩放
              resolve({
                width: width,
                height: height
              });
              return;
            }

            // ---- 情况 3：横向超宽图（宽度远大于高度） ----
            if (naturalW / naturalH > 2) {
              const scale = thumbHeight / naturalH;
              width = naturalW * scale;
              height = thumbHeight;

							if(+width > +sys.windowWidth * 0.7) {
								width = width*0.35
								height = height*0.4
							}

              resolve({
                width: width,
                height: height
              });
              return;
            }

            // ---- 情况 4：普通大图（宽或高超限） ----
            if (naturalW > maxChatWidth) {
              width = maxChatWidth * 0.5;
              height = naturalH * (width / naturalW);  // 根据宽高比缩放
              resolve({
                width: width,
                height: height
              });
              return;
            }

            if (naturalH > maxChatHeight) {
              const scale = maxChatHeight / naturalH;
              height = maxChatHeight;
              width = naturalW * scale * 0.7;  // 根据宽高比缩放
              resolve({
                width: width,
                height: height
              });
            }
          }
        });
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}



export async function downloadToPublicDownloadFolder(url, filename) {
  const main = plus.android.runtimeMainActivity();
  const Context = plus.android.importClass("android.content.Context");
  const Environment = plus.android.importClass("android.os.Environment");
  const Uri = plus.android.importClass("android.net.Uri");
  const Intent = plus.android.importClass("android.content.Intent");
  const Settings = plus.android.importClass("android.provider.Settings");
  const DownloadManager = plus.android.importClass("android.app.DownloadManager");
  const Request = plus.android.importClass("android.app.DownloadManager$Request");
  const File = plus.android.importClass("java.io.File");

  // ✅ 检查权限（Android 11+）
  if (plus.os.name === 'Android' && parseInt(plus.os.version) >= 11) {
    if (!Environment.isExternalStorageManager()) {
      uni.showModal({
        title: "权限申请",
        content: "需要打开“所有文件访问权限”才能保存到公共目录，请在设置中开启",
        confirmText: "去开启",
        success(res) {
          if (res.confirm) {
            const intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + main.getPackageName()));
            main.startActivity(intent);
          }
        }
      });
      return;
    }
  }

  // ✅ 获取 DownloadManager 服务
  const dm = main.getSystemService(Context.DOWNLOAD_SERVICE);
  plus.android.importClass(dm); // 必须导入实例方法

  const downloadUri = Uri.parse(url);
  const request = new Request(downloadUri);

  request.setTitle(filename);
  request.setDescription("正在下载中...");
  request.setMimeType("*/*");
  request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

  // ✅ 下载到公有 Download 目录
  const downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
  const file = new File(downloadPath, filename);
  request.setDestinationUri(Uri.fromFile(file));

  // ✅ 执行下载
  dm.enqueue(request);

  uni.showToast({
    title: "已开始下载",
    icon: "success"
  });
}

/**
* 通过content:// Uri获取文件详情（name、size）和临时文件路径（如果本地路径不可用）
* @param {string} uriStr 文件的content uri字符串，比如 "content://..."
* @returns {Promise<{name:string, size:number, tempFilePath:string}>}
*/
export function getFileDetails(uriStr) {
	return new Promise((resolve, reject) => {
		try {
			const main = plus.android.runtimeMainActivity();
			const contentResolver = main.getContentResolver();
			const UriClass = plus.android.importClass("android.net.Uri");
			const uri = UriClass.parse(uriStr);

			// 查询文件名和大小
			const cursor = contentResolver.query(uri, null, null, null, null);
			plus.android.importClass(cursor);

			let name = null;
			let size = -1;
			if (cursor && cursor.moveToFirst()) {
				const nameIndex = cursor.getColumnIndex("_display_name");
				const sizeIndex = cursor.getColumnIndex("_size");
				if (nameIndex >= 0) name = cursor.getString(nameIndex);
				if (sizeIndex >= 0) size = cursor.getLong(sizeIndex);
				cursor.close();
			}

			if (!name) name = "tempfile";

			// 如果没大小或者大小异常，就保存临时文件再获取大小
			if (size <= 0) {
				// 保存临时文件，计算大小
				this.saveUriToTempFile(uri, name).then(tempFilePath => {
					plus.io.getFileInfo({
						filePath: tempFilePath,
						success: (fileInfo) => {
							resolve({
								name,
								size: fileInfo.size,
								tempFilePath
							});
						},
						fail: () => {
							resolve({
								name,
								size: 0,
								tempFilePath
							});
						}
					});
				}).catch(err => reject(err));
			} else {
				// 只返回元信息，路径为空（可根据需要调用saveUriToTempFile保存临时文件）
				resolve({
					name,
					size,
					tempFilePath: null
				});
			}
		} catch (e) {
			reject(e);
		}
	});
}


/**
 * 保存content:// Uri到临时文件
 * @param {android.net.Uri} uri
 * @param {string} fileName 文件名
 * @returns {Promise<string>} 返回临时文件路径
 */
export function saveUriToTempFile(uri, fileName) {
	return new Promise((resolve, reject) => {
		try {
			const main = plus.android.runtimeMainActivity();
			const contentResolver = main.getContentResolver();
			const InputStream = plus.android.importClass("java.io.InputStream");
			const FileOutputStream = plus.android.importClass("java.io.FileOutputStream");
			const File = plus.android.importClass("java.io.File");

			const inputStream = contentResolver.openInputStream(uri);
			if (!inputStream) return reject("无法打开输入流");

			// 临时文件路径
			const tempPath = plus.io.convertLocalFileSystemURL("_downloads/") + fileName;
			const file = new File(tempPath);
			const outputStream = new FileOutputStream(file);

			const buffer = plus.android.newObject("byte[]", 1024);
			let len = 0;

			while ((len = inputStream.read(buffer)) !== -1) {
				outputStream.write(buffer, 0, len);
			}
			inputStream.close();
			outputStream.close();

			resolve(tempPath);
		} catch (e) {
			reject(e);
		}
	});
}

export function extractHrefOrReplace(text) {
    const anchorRegex = /<a\s+[^>]*href="([^"]+)"[^>]*>(.*?)<\/a>/gi;

    if (!anchorRegex.test(text)) {
        return text;
    }

    const singleAnchorMatch = text.trim().match(/^<a\s+[^>]*href="([^"]+)"[^>]*>.*<\/a>$/i);
    if (singleAnchorMatch) {
        return singleAnchorMatch[1];
    }

    return text.replace(anchorRegex, (match, href) => href);
}
